<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection"
          content="telephone=no,email=no,date=no,address=no">
    <title>周边服务</title>
    <link rel="stylesheet" type="text/css"
          href="${ctxPath}/static/assets/aui/css/aui.css"/>
    <!-- jQuery Include -->
    <script type="text/javascript" src="${ctxPath}/static/assets/scripts/jquery.min.js"></script>
    <script type="text/javascript" src="${ctxPath}/static/assets/aui/script/api.js"></script>
    <script type="text/javascript" src="${ctxPath}/static/assets/aui/script/aui-sharebox.js"></script>
    <script type="text/javascript" src="${ctxPath}/static/js/common.js"></script>
    <style type="text/css" media="screen">
        body,
        html,
        #mapContainer {
            width: 100%;
            height: 100%;
            overflow: hidden;
            margin: 0;
            font-family: "微软雅黑";
        }
        #search{
            position: fixed;
            z-index: 999;
            top: 20px;
            right: 15px;
            background-color: #03a9f4;
            color: white;
            width: 66px;
            text-align: center;
            border-radius: 10%;
        }
        #content{
            width: 100%;
            height: 55%;
            position: fixed;
            bottom: 0;
            z-index: 999;
            background-color: white;
            display: none;
            overflow-y: auto;
        }
        #que{
            position: absolute;
            bottom: 0;
        }
        .aui-margin-r-1{
            float: right;
            position: absolute;
            right: 0px;
            height: 28px;
            top: 0px;
            line-height: 2;
        }
        #content{
            background-color: #f5f5f5;
        }
        #loading>img{
            top: 50%;
            position: absolute;
            text-align: center;
            width: 50px;
            height: 50px;
            left: 50%;
        }
    </style>
</head>

<body>
<div id="mapContainer"></div>
<!--增加搜索框-->
<div id="search" >
    <i class="aui-iconfont aui-icon-search"></i>
    筛选
</div>
<div id="content">
    <header class="aui-bar aui-bar-nav">搜索内容</header>
    <div class="aui-searchbar" id="area">
        <div class="aui-searchbar-input aui-border-radius" tapmode >
            <i class="aui-iconfont aui-icon-search"></i>
            <form>
                <input type="search" placeholder="请输入搜索位置信息" id="areainfo" data_lng="" data_lat="">
            </form>
            <div class="aui-list-item-inner aui-list-item-center aui-list-item-btn">
                <div class="aui-btn aui-btn-info aui-margin-r-1" id="search-input">搜索</div>
            </div>
        </div>
    </div>
    <div class="aui-content aui-margin-b-15" id="areas">
        <ul class="aui-list aui-list-in">
            <li class="aui-list-header">
                周边地址
            </li>
        </ul>
        <ul class="aui-list aui-list-in" id="away" style="height:100px;overflow-y: auto">
        </ul>
    </div>
    <div class="aui-content aui-margin-b-15">
        <ul class="aui-list aui-form-list">
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">
                        性别
                    </div>
                    <div class="aui-list-item-input" id="sex">
                        <label><input class="aui-radio" type="radio" name="sex" value="2" checked> 不限</label>
                        <label><input class="aui-radio" type="radio" name="sex" value="0"> 女</label>
                        <label><input class="aui-radio" type="radio" name="sex" value="1"> 男</label>
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">
                        是否在线
                    </div>
                    <div class="aui-list-item-input">
                        <input type="checkbox" class="aui-switch" checked id="isOnline">
                    </div>
                </div>
            </li>
        </ul>
    </div>
    <div class="aui-btn aui-btn-info aui-btn-block aui-btn-sm" id="que">确认</div>
</div>
<!--loading图显示-->
<div id="loading">
    <img src="${ctxPath}/static/assets/images/loading.gif" alt="loading.." />
</div>

<footer class="aui-bar aui-bar-tab" id="footer">
    <div class="aui-bar-tab-item aui-active">
        <i class="aui-iconfont aui-icon-paper"></i>
        <div class="aui-bar-tab-label">周边服务</div>
    </div>
    <div class="aui-bar-tab-item" onclick="artificerPage()">
        <i class="aui-iconfont aui-icon-menu"></i>
        <div class="aui-bar-tab-label">技师列表</div>
    </div>
    <div class="aui-bar-tab-item" onclick="orderPage()">
        <i class="aui-iconfont aui-icon-cart"></i>
        <div class="aui-bar-tab-label">订单列表</div>
    </div>
    <div class="aui-bar-tab-item " onclick="minePage()">
        <i class="aui-iconfont aui-icon-my"></i>
        <div class="aui-bar-tab-label">我的</div>
    </div>
</footer>
<script type="text/javascript">
    apiready = function(){
        api.parseTapmode();
    }
    $(function () {

        $("#search").click(function () {
            $("#areainfo").val("");
            $("#away").hide();
            $("#away").html("");
            if($("#content").is(':hidden')){
                $("#content").fadeIn("slow");
            }else{
                $("#content").fadeOut("slow");
            }
        })
        //---------------------------查询确认----------
        $("#que").click(function () {
            $("#content").fadeOut("slow");
            var lat=$("#areainfo").attr("data_lat");
            var lng=$("#areainfo").attr("data_lng");
            //去提交查询信息
            var sex = $('input[name="sex"]:checked').val();
            var isOnline=$("#isOnline:checked").length>0?"1":"0";
            if(!lng||!lat){
                var position=localStorage.getItem("position");
                if (position) {
                    var obj = JSON.parse(position); // --> parse error
                    lng=obj.longitude;
                    lat=obj.latitude;
                }else{
                    return;
                }
            }
            //后台查询
            $.ajax({
                type: "POST",
                url: "${ctxPath}/wechat/public/searchByparam",
                dataType: 'json',
                async: false,
                data:{
                    "lat":lat,
                    "lng":lng,
                    "isOnline":isOnline,
                    "sex":sex,
                    "distance":50
                },
                success: function (result) {
                    //初始化数据
                    if(result.status=="0000"){
                        initOne(result.data, lat, lng);
                        $("#areainfo").attr("data_lng","");
                        $("#areainfo").attr("data_lat","");
                    }
                }
            });
        })
        //--------------------------点击周边搜索----------------
        $("#search-input").click(function () {
            // 失去焦点查询
            var  searchContent=$("#areainfo").val();
            if(!searchContent){
                return
            }
            //查询
            $.ajax({
                type: "get",
                url: "${ctxPath}/wechat/public/getAways",
                dataType: 'json',
                async: false,
                data:{
                  "area":"成都",
                  "location":searchContent
                },
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                   if(result.status=="0000"&&result.data.message=="ok"){
                       $("#away").show();
                       var array=result.data.result;
                       var  str="";
                       for(var  i in array){ // console.log("地址名称："+array[i].name)  ;console.log("地址经纬度："+array[i].location)
                           if(!array[i].uid){
                               continue;
                           }
                           str+=" <li onclick='getAway(this)' class=\"aui-list-item aui-list-item-middle\">\n" +
                               "                <div class=\"aui-list-item-inner aui-list-item-arrow\"  data_lat='"+array[i].location.lat+"' data_lng='"+array[i].location.lng+"' >\n" +
                               "                    "+array[i].name+"\n" +
                               "            </div></li>";
                       }
                       $("#away").html(str);
                   }else{//获取定位周边信息失败
                       alert("获取定位周边信息失败")
                   }
                }
            });
        })
    })
    //点击获取地理位置信息
    function getAway(ele) {
        $("#away").hide();
        var  name=$(ele).find("div").text();
        var  lat=$(ele).find("div").attr("data_lat");
        var  lng=$(ele).find("div").attr("data_lng");
        $("#areainfo").val(name);
        $("#areainfo").attr("data_lat",lat);
        $("#areainfo").attr("data_lng",lng);
    }
    
    
</script>
<!-- map -->
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=b5Kjd0zcpNax99AmviHxR2tXKIMGDnDA"></script>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<!--获取微信地理位置需要的zepto.js-->
<script src="${ctxPath}/static/js/zepto.min.js"></script>
<!--获取微信地理位置需要的demojs-->
<script>
    //========================优化 十分钟清理一下定位============================
    var position = localStorage.getItem("position");
    if (position) {
        var obj = JSON.parse(position); // --> parse error
        callback(obj.latitude, obj.longitude);
    } else {
        //=================校验微信签名信息=============================
        $.ajax({
            type: "get",
            url: "${ctxPath}/wechat/public/getSign?url=" + encodeURIComponent(location.href.split('#')[0]),
            dataType: 'json',
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                if (result.status == "0000") {
                    var datas = result.data;
                    wx.config({
                        debug: false,  // 开启调试模式
                        appId: datas.appId,    // 必填，公众号的唯一标识
                        timestamp: datas.timestamp,  // 必填，生成签名的时间戳
                        nonceStr: datas.noncestr, // 必填，生成签名的随机串
                        signature: datas.signature,// 必填，签名，
                        jsApiList: ["getLocation"] // 必填，需要使用的JS接口列表，
                    })
                }
            }
        });
        //=================获取微信地理位置=============================
        wx.ready(function () {
            //获取微信地理位置
            wx.getLocation({
                success: function (res) {
                    var lat = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    var lng = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    localStorage.setItem("position", JSON.stringify({latitude: lat, longitude: lng}));
                    callback(lat, lng);
                },
                cancel: function (res) {
                    //拒绝授权择定位中心城市
                    var geolocation = new BMap.Geolocation();
                    geolocation.getCurrentPosition(function (r) {
                        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                            localStorage.setItem("position", JSON.stringify({
                                latitude: r.latitude,
                                longitude: r.longitude
                            }));
                            callback(r.latitude, r.longitude);
                        } else {
                            alert('failed' + this.getStatus());
                        }
                    });
                },
                complete: function (res) {
                }
            });
        });
    }
    //回调函数调用
    function callback(lat, lng) {
        //==================百度转换位置============================
        $.ajax({
            type: "POST",
            url: "${ctxPath}/wechat/public/getLocation",
            dataType: "json",
            async: false,
            data: {
                lat: lat,
                lng: lng
            },
            success: function (result) {
                if (result.status == "0000") {
                    var position = result.data.result[0];
                    lat = position.y;
                    lng = position.x;
                } else {
                    alert("地址转换出错!");
                    alert(JSON.stringify(result));
                }
            }
        });
        //==============================================
        // 创建地理编码实例
        var myGeo = new BMap.Geocoder();
        // 根据坐标得到地址描述
        myGeo.getLocation(new BMap.Point(lng, lat), function (result) {
            if (result) {
                // alert(result.address);
            }
        });
        //初始化加载基础数据
        var array = new Array();
        $.ajax({
            type: "POST",
            url: "${ctxPath}/artificerMeans/orderList",
            dataType: "json",
            async: false,
            data: {
                consumerLongitude: lng,
                consumerLatitude: lat,
                distance: 200
            },
            success: function (result) {
                if (result.status = "0000") {
                    array = result.data;
                    localStorage.setItem("arts", JSON.stringify(array));//以“key”为名称存储一个值“value”
                    initOne(array, lat, lng);
                }
            }
        });
    }

    //初始化数据
    function initOne(array, lat, lng) {
        // 百度地图API功能
        var map = new BMap.Map("mapContainer"); // 创建Map实例
        map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
        var point = new BMap.Point(lng, lat); //创建中心点
        map.centerAndZoom(point, 13); // 初始化地图,设置中心点坐标和地图级别
        map.clearOverlays();
        var myIcon = new BMap.Icon("http://www.tyler.org.cn/images/small/wodeweizhi.png?x-oss-process=image/resize,h_77/circle,r_100/format,png", new BMap.Size(33, 33)); //自定义点图标
        var marker = new BMap.Marker(point, {
            offset: new BMap.Size(0, 0) //偏移
            , icon: myIcon //图标
        });
        map.addOverlay(marker); //把标记覆盖物添加到地图
        map.panTo(point); //转到该点位置

        /*------------------------------------自定义核心代码--------------------------------------------------*/
        //创建自定义覆盖物构造函数
        function ComplexCustomOverlay(param) {
            this.point = param.point; //覆盖物坐标点
            this.content = param.content || ''; //覆盖内容
            this.zIndex = param.zIndex || 1; //覆盖物内容层级
            this.boxClass = param.boxClass || ''; //覆盖物容器class名称
            this.boxStyle = cssText(param.boxStyle); //覆盖物容器样式
            this.arrowClass = param.arrowClass || ''; //覆盖物箭头class名称
            this.arrowStyle = cssText(param.arrowStyle); //覆盖物箭头样式
        }
        //把百度地图遮盖物对象赋值给构造函数原型对象
        ComplexCustomOverlay.prototype = new BMap.Overlay();
        // //自定义覆盖物添加事件方法
        // ComplexCustomOverlay.prototype.addEventListener = function(event,fun){
        //     this.boxClass['on'+event] = fun;
        // }

        //初始化创建覆盖物
        ComplexCustomOverlay.prototype.initialize = function (map) {
            this.map = map;
            this.box = document.createElement('div');
            this.box.className = this.boxClass;
            this.box.style.cssText = this.boxStyle;
            this.box.innerHTML = this.content;
            this.arrow = document.createElement('div');
            this.arrow.className = this.arrowClass;
            this.arrow.style.cssText = this.arrowStyle;

            //6、自定义覆盖物添加事件方法
            ComplexCustomOverlay.prototype.addEventListener = function (event, fun) {
                this.box['on' + event] = fun;
            }
            map.getPanes().labelPane.appendChild(this.box);
            map.getPanes().labelPane.appendChild(this.arrow);
            return this.box;
        };
        //地图拖动调用事件
        ComplexCustomOverlay.prototype.draw = function () {
            mapDraw(this);
        };

        //计算覆盖物在地图上的位置
        function mapDraw(_this) {
            var pixel = map.pointToOverlayPixel(_this.point);
            _this.box.style.left = pixel.x - parseInt(getStyle(_this.box, 'width')) / 2 - (parseInt(getStyle(_this.box, 'padding-left')) + parseInt(getStyle(_this.box, 'padding-right'))) / 2 + "px";
            _this.box.style.bottom = -pixel.y + parseInt(getStyle(_this.arrow, 'height')) + "px";

            _this.arrow.style.left = (pixel.x - parseInt(getStyle(_this.arrow, 'width')) / 2-10) + "px";
            _this.arrow.style.bottom =( -pixel.y+2) + "px";
        }

        //容器css样式配置
        var boxCss = {
            'position': 'absolute',
            'width': '50px',
            'height': '50px',
            // 'padding': '24px',
            'background-color': '#fff',
            'border-radius': '50%',
            'white-space': 'nowrap',
            'box-shadow': 'rgb(0, 0, 0) 0px 1px 9px -3px',
            'border': '2px solid #009688'
        };
        //箭头css样式配置
        // var arrowCss = {
        //     'position': 'absolute',
        //     'margin-left': '10px',
        //     'float': 'left',
        //     'width': '0',
        //     'height': '0',
        //     'overflow': 'hidden',
        //     'border-width': '10px',
        //     'border-style': 'solid',
        //     'border-color': '#009688 transparent transparent transparent'
        // };
        for (var i = 0; i < array.length; i++) {
            var art = array[i];
            var imgUrl = "http://www.tyler.org.cn/" + art.imgUrl + "?x-oss-process=image/resize,h_99/circle,r_100/format,png";
            //实例化覆盖物对象
            var myCompOverlay = new ComplexCustomOverlay({
                point: new BMap.Point(art.longitude, art.latitude),
                content: "<img class='artImg'  src='" + imgUrl + "'/>",
                boxClass: 'box',
                boxStyle: boxCss,
                // arrowClass: 'arrow',
                // arrowStyle: arrowCss,
                zIndex: 1
            });
            //地图缩放重新计算覆盖物位置
            map.addEventListener("zoomend", function () {
                mapDraw(myCompOverlay);
            });
            //把自定义覆盖物添加到地图
            map.addOverlay(myCompOverlay);

            myCompOverlay.addEventListener("click", function () {
                console.log(2111111111111);
            });
        }

    }
    /*-----------------------------------自定义核心代码结束---------------------------------------------------*/

    /*--下面为辅助代码------------------------------------------------------------------------------------*/
    //获取元素样式
    function getStyle(node, attr) {
        if (typeof getComputedStyle != 'undefined') {
            var value = getComputedStyle(node, null).getPropertyValue(attr);
            return attr == 'opacity' ? value * 100 : value; //兼容不透明度，如果是不透明度，则返回整数方便计算
        } else if (typeof node.currentStyle != 'undefined') { //如果是IE
            if (attr == 'opacity') { //兼容不透明度
                return Number(node.currentStyle.getAttribute('filter').match(/(?:opacity[=:])(\d+)/)[1]);
            } else {
                return node.currentStyle.getAttribute(attr);
            }
        }
    }
    //css样式字符串处理
    function cssText(style) {
        var css = '';
        if (typeof style == 'string') {
            css = style;
        } else if (typeof style == 'object') {
            for (var i in style) {
                css += i + ':' + style[i] + ';';
            }
        }
        return css;
    }
</script>
</body>
<script type="text/javascript">
    function artificerPage() {
        location.href = "${ctxPath}/wechat/public/toArtificerListPage";
    }

    function orderPage() {
        location.href = "${ctxPath}/wechat/public/toOrderPage";
    }

    function minePage() {
        location.href = "${ctxPath}/wechat/public/toMinePage";
    }
</script>
</html>